package yt.demo.appcoresystem.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import yt.demo.appcommonbean.exception.LogicException;
import yt.demo.appcommondb.base.BaseService;
import yt.demo.appcommondb.vo.ConditionVO;
import yt.demo.appcoresystem.entity.SystemDept;
import yt.demo.appcoresystem.entity.SystemUser;
import yt.demo.appcoresystem.entity.SystemUserDept;
import yt.demo.appcoresystem.mapper.SystemUserDeptMapper;
import yt.demo.appcoresystem.service.ISystemDeptService;
import yt.demo.appcoresystem.service.ISystemUserDeptService;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class SystemUserDeptService extends BaseService<SystemUserDept, SystemUserDeptMapper> implements ISystemUserDeptService {


    ISystemDeptService deptService;

    @Autowired
    public SystemUserDeptService(SystemUserDeptMapper mapper, ISystemDeptService deptService) {
        super(mapper, SystemUserDept.class);
        this.deptService = deptService;
    }

    @Override
    protected List<ConditionVO<SystemUserDept, ?>> whereConditions(SystemUserDept params) {
        return List.of();
    }

    public void syncDept(Long userId, List<Long> deptIds) {

        List<SystemUserDept> userDeptList = userDeptList(List.of(userId));

        //根据 DeptId 查询所有部门
        List<Long> currentIds = getDeptIds(userDeptList);

        List<Long> toDelete = currentIds.stream()
                .filter(deptId -> !deptIds.contains(deptId))
                .toList();

        // 计算出需要插入 ID
        List<Long> toInsert = deptIds.stream()
                .filter(deptId -> !currentIds.contains(deptId))
                .toList();

        // 删除需要删除的关联
        if (!toDelete.isEmpty()) {
            deleteUserDept(userId, toDelete);
        }
        // 批量插入新的关联
        if (!toInsert.isEmpty()) {
            List<SystemUserDept> userDepts = toInsert.stream()
                    .map(deptId -> {
                        SystemUserDept systemUserDept = new SystemUserDept();
                        systemUserDept.setUserId(userId);
                        systemUserDept.setDeptId(deptId);
                        return systemUserDept;
                    })
                    .toList();
            if (batchInsert(userDepts)) {
                throw new LogicException("同步失败");
            }
        }
    }

    public void deleteUserDept(Long userId, List<Long> deptIds) {
        List<ConditionVO<SystemUserDept, ?>> conditions = new ArrayList<>();
        conditions.add(ConditionVO.createCondition(SystemUserDept::getUserId, "eq", userId));
        conditions.add(ConditionVO.createCondition(SystemUserDept::getDeptId, "in", deptIds));
        deleteWhere(conditions);
    }

    public void belongsToDept(List<Long> userIds, List<SystemUser> list) {
        if (userIds.isEmpty()){
            return;
        }
        List<SystemUserDept> userDeptList = userDeptList(userIds);

        //根据 DeptId 查询所有部门
        List<Long> beIds = getDeptIds(userDeptList);
        if (beIds.isEmpty()){
            return;
        }
        //批量查询所有部门
        List<SystemDept> beList = this.deptService.selectBatchIds(beIds);

        //创建一个映射用户ID到部门列表的映射
        Map<Long, List<SystemDept>> userDeptMap = userDeptList.stream()
                .collect(Collectors.groupingBy(SystemUserDept::getUserId,
                        Collectors.mapping(userBe ->
                                        beList.stream().filter(be -> be.getId().equals(userBe.getDeptId()))
                                                .findFirst().orElse(null),
                                Collectors.toList())));
        // 填充用户的部门信息
        list.forEach(user -> {
            List<SystemDept> userDeptLists = userDeptMap.get(user.getId());
            if (userDeptLists != null) {
                user.setDeptIds(userDeptLists.stream().map(SystemDept::getId).collect(Collectors.toList()));
                user.setDeptName(userDeptLists.stream().map(SystemDept::getName).collect(Collectors.joining(", ")));
            }
        });
    }

    public List<Long> deptToUserIds(List<Long> deptIds) {
        LambdaQueryWrapper<SystemUserDept> wrapper = new LambdaQueryWrapper<>();
        List<SystemUserDept> list = mapper.selectList(
                wrapper.in(SystemUserDept::getDeptId, deptIds)
        );
        return list.stream()
                .map(SystemUserDept::getUserId)
                .distinct() // 去重
                .toList();
    }

    private List<SystemUserDept> userDeptList(List<Long> userIds) {
        LambdaQueryWrapper<SystemUserDept> wrapper = new LambdaQueryWrapper<>();
        return mapper.selectList(
                wrapper.in(SystemUserDept::getUserId, userIds)
        );
    }

    private List<Long> getDeptIds(List<SystemUserDept> list) {
        return list.stream()
                .map(SystemUserDept::getDeptId)
                .distinct() // 去重
                .toList();
    }
}
